package cz.schovjan.proj.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import cz.schovjan.proj.dao.IBandDao;
import cz.schovjan.proj.dao.ISongDao;
import cz.schovjan.proj.dto.Song;
import cz.schovjan.proj.entity.BandEntity;
import cz.schovjan.proj.entity.SongEntity;
import cz.schovjan.proj.service.ISong;

/**
 * Implementace rozhrani ISong pro praci se pisnemi.
 * @author schovjan
 *
 */
@Transactional
public class SongImpl implements ISong {
	
	@Autowired
	private ISongDao songDao;
	
	@Autowired
	private IBandDao bandDao;	

	
	@Override
	public void add(String nameCs, String nameOriginal, String author, String arrange, String description) {
		SongEntity se = new SongEntity();
		se.setNameCs(nameCs);
		se.setNameOriginal(nameOriginal);
		se.setAuthor(author);
		se.setArrange(arrange);
		se.setDescription(description);
		
		songDao.add(se);
	}
	
	
	@Override
	public List<Song> findOtherSongs(Integer id) {
		List<Song> result = new ArrayList<Song>();
		List<SongEntity> seAll = songDao.findAll();
		BandEntity band = bandDao.find(id);
		
		for (SongEntity se : band.getSongs()) {
			seAll.remove(se);
		}
		for (SongEntity se : seAll) {
			result.add(loadSong(se));
		}
		
		return result;
	}

	
	/**
	 * Vrati nasetovanou pisen.
	 * @param me
	 * @return
	 */
	private Song loadSong(SongEntity se) {
		
		if (se==null) {
			return null;
		}
		Song s = new Song();
		s.setId(se.getId());
		s.setNameCs(se.getNameCs());
		s.setNameOriginal(se.getNameOriginal());
		s.setArrange(se.getArrange());
		s.setAuthor(se.getAuthor());
		s.setDescription(se.getDescription());
		
		return s;
	}
	
	
	@Override
	public Song find(Integer id) {
		SongEntity se = songDao.find(id);

		return loadSong(se);
	}
	
	
	@Override
	public void save(Integer id, String nameCs, String nameOriginal, String author, String arrange, String description) {
		SongEntity se = songDao.find(id);
		se.setNameCs(nameCs);
		se.setNameOriginal(nameOriginal);
		se.setAuthor(author);
		se.setArrange(arrange);
		se.setDescription(description);
	}
	
}
